<template>
  <div class="watermark-img-wrapper">
    <img class="watermark-img" :src="source" alt="">
    <div class="watermark-overlay" :style="{ backgroundImage: `url(${watermark})`, opacity }"></div>
  </div>
</template>

<script>
export default {
  props: {
    source: {
      type: String,
      required: true,
    },
    name: {
      type: String,
      default: '',
    },
    opacity: {
      type: Number,
      default: 0.5,
    },
  },
  data() {
    return {
      watermarkUrl: '',
    }
  },
  mounted() {
    const img = new Image()
    img.crossOrigin = 'anonymous'
    img.onload = () => {
      const canvas = document.createElement('canvas')
      const context = canvas.getContext('2d')
      canvas.width = img.width
      canvas.height = img.height

      // draw the original image on canvas
      context.drawImage(img, 0, 0)

      // draw the name or datetime on canvas
      const text = this.name || new Date().toLocaleString()
      context.font = '16px sans-serif'
      context.fillStyle = 'white'
      context.fillText(text, 10, canvas.height - 10)

      this.watermarkUrl = canvas.toDataURL()

      // update the position of the overlay
      const wrapper = this.$el.querySelector('.watermark-img-wrapper')
      const position = wrapper.getBoundingClientRect()
      const overlay = this.$el.querySelector('.watermark-overlay')
      overlay.style.left = `${position.left}px`
      overlay.style.top = `${position.top}px`
      overlay.style.width = `${position.width}px`
      overlay.style.height = `${position.height}px`
    }
    img.src = this.source
  },
}
</script>

<style scoped>
.watermark-img-wrapper {
  position: relative;
}

.watermark-img {
  display: block;
  max-width: 100%;
  height: auto;
}

.watermark-overlay {
  position: absolute;
  background-repeat: no-repeat;
  background-size: contain;
}
</style>